package com.demo;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.Scanner;

public class MyNacosConfig {
    public static void main(String[] args) throws NacosException {

        String serverAddr = "localhost";
        String dataId = "luohu.properties"; // dataId
        String group = "DEFAULT_GROUP"; // group
        Properties properties = new Properties();
        // nacos-server地址
        properties.put("serverAddr", serverAddr);
        // namespace/tenant
        properties.put("namespace", "de1f6260-cf8b-4722-ae75-4aa9cf8f5989");
        ConfigService configService = NacosFactory.createConfigService(properties);
        // 1. 注册监听
        configService.addListener(dataId, group, new AbstractListener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                /**只要修改了配置，才会触发监听器方法
                 * 在长轮询方法中触发回调  判断当前的Md5和CacheData中持有的md5是否一致
                 * cacheData.checkListenerMd5();*/
                System.out.println("receive config info ：" + configInfo);
            }
        });
        // 2. 查询初始配置
        String config = configService.getConfig(dataId, group, 3000);
        System.out.println("init config : " + config);
        // 3. 修改配置
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String next = scanner.next();
            if ("exit".equals(next)) {
                break;
            }
            configService.publishConfig(dataId, group, next);
        }
    }
}
